/**
 * 注册
 */
import { useReqBody, generateUser } from "@sker/runtime";
import { useTransaction, HttpError, toSuccess } from "@sker/core";
import { SysUser } from "@sker/entities";
import { DependencyContainer } from "tsyringe";

import { z } from "zod";
const input = z.object({
    username: z.string(),
    password: z.string(),
    realname: z.optional(z.string()),
    mobile: z.optional(z.string()),
    group_id: z.string(),
    uid: z.optional(z.string()),
})
export default async (injector: DependencyContainer) => {
    const body = input.parse(useReqBody())
    await useTransaction(async manager => {
        if (body.uid) {
            const sysUser = await manager.findOne(SysUser, {
                where: { uid: body.uid },
                select: {
                    uid: true
                }
            });
            if (!sysUser) throw new HttpError(`账户不存在`)
            const sysUserUsername = await manager.findOne(SysUser, {
                where: { username: body.username },
                select: {
                    uid: true
                }
            });
            if (sysUserUsername) throw new HttpError(`用户名已存在`)
            const user = await generateUser(body.username, body.password)
            const extra: any = {};
            if (body.realname) extra.realname = body.realname;
            if (body.mobile) extra.mobile = body.mobile;
            await manager.update(SysUser, sysUser.uid, { ...user, group_id: body.group_id, ...extra })
            return;
        } else {
            const sysUser = await manager.findOne(SysUser, {
                where: { username: body.username },
                select: {
                    uid: true
                }
            });
            if (sysUser) throw new HttpError(`账户已存在`)
            // 加密password
            const user = await generateUser(body.username, body.password)
            const extra: any = {};
            if (body.realname) extra.realname = body.realname;
            if (body.mobile) extra.mobile = body.mobile;
            await manager.insert(SysUser, { ...user, group_id: body.group_id, ...extra })
            return;
        }
    })
    return toSuccess({})
}
